package site.lanmushan.framework.mapper.provider;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.MappedStatement;
import site.lanmushan.framework.mapper.util.SlashSqlHelper;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.EntityTable;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.Set;

/**
 * @author Administrator
 */
@Slf4j
public class SelectQueryInfoListProvider extends MapperTemplate {
    public SelectQueryInfoListProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public String selectQueryInfoWrapperList(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        EntityTable entityTable = EntityHelper.getEntityTable(entityClass);

        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(" from "+EntityHelper.getEntityTable(entityClass).getName());
        this.setResultType(ms, entityClass);
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        EntityHelper.getEntityTable(entityClass);
        if (columnList.size() == 1) {
            sql.append("  <trim prefix=\"where\" prefixOverrides=\"and|or\" suffixOverrides=\"and|or\">\n" +
                    "            <foreach collection=\"query.param\" index=\"key\" item=\"it\" separator=\"and\" open=\" (\" close=\") \">\n" +
                    "                <if test=\"it.operate =='in'\">\n" +
                    "                    ${it.column} ${it.operate} (#{it.value})\n" +
                    "                </if>\n" +
                    "                <if test=\"it.operate !='in'\">\n" +
                    "                    ${it.column} ${it.operate} #{it.value}\n" +
                    "                </if>\n" +
                    "            </foreach>\n" +
                    "        </trim>");
            log.info("結果:{}",sql.toString());
            return sql.toString();
        } else {
            throw new MapperException("继承 deleteByIds 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
    }

}
